package com.huanghe.controller;

import com.huanghe.mgr.TokenByPassword;
import org.apache.commons.io.IOUtils;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStream;

public class JobTest {

    public static void main(String[] args) throws IOException {
        String url = "https://11b3bb4c-b22a-11ec-ab57-0255ac100044.cce.cn-southwest-2.myhuaweicloud.com/apis/batch/v1/namespaces/dev/jobs";
        InputStream stream = JobTest.class.getClassLoader().getResourceAsStream("job.json");
        String json = IOUtils.toString(stream, "utf-8");
        String token = TokenByPassword.getToken();
        String resp = doPostResp(url, json, token);
    }

    /**
     * 发送 POST 请求，JSON 形式，返回 HttpResponse
     *
     * @param url url
     * @param json json字符串
     * @return POTS结果
     */
    public static String doPostResp(String url, String json, String token) throws IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        String resString = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            // 设置header信息
            httpPost.setHeader(new BasicHeader("Content-Type", "application/json"));
            httpPost.setHeader(new BasicHeader("X-Auth-Token", token));

            // 装填参数
            StringEntity s = new StringEntity(json, "utf-8");
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            // 设置参数到请求对象中
            httpPost.setEntity(s);

            // 执行请求
            response = httpclient.execute(httpPost);
            System.out.println("请求返回的状态码："+ response.getStatusLine().getStatusCode());
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 201) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println("内容长度：" + content.length());
                System.out.println("返回的内容：" + content);
                return "success：" + content;
            }
        } catch (Exception e) {
            System.out.println("系统错误：" + e.getMessage() + "---" + e.toString() + "====" + e);
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
        return "failed";
    }
}
